package com.apes.report.ext;

import com.bstek.ureport.exception.ReportComputeException;
import com.bstek.ureport.provider.image.ImageProvider;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.context.WebApplicationContext;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * @author cxm
 * @since 2019年3月26日
 */
@Component
public class ReportImageProvider implements ImageProvider, ApplicationContextAware {
    private ApplicationContext applicationContext;
    private String baseWebPath;
    @Value("${pic.url}")
    private String url;
    @Override
    public InputStream getImage(String path) {
        try {
            if(path.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX) || path.startsWith("/WEB-INF")){
                return applicationContext.getResource(path).getInputStream();
            }else{
                path=removePrefix(path);

               String BaseURL= url + path;
               URL url= new URL(BaseURL);
               HttpURLConnection con = (HttpURLConnection) url.openConnection();
               con.setRequestMethod("GET");
               con.setConnectTimeout(5*10000);
               return con.getInputStream();
            }
        } catch (IOException e) {
            throw new ReportComputeException(e);
        }
    }
    @Override
    public boolean support(String path) {
//        if(path.endsWith(".jpg")|| path.endsWith(".JPG")){
//            return true;
//        }else{
//            return false;
//        }
        return true;
    }
    private String removePrefix(String file){
        return file.replace("url:","");
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(applicationContext instanceof WebApplicationContext){
            WebApplicationContext context=(WebApplicationContext)applicationContext;
           // D:\grxm\eclipse64\apache-tomcat-8.0.44\webapps\ytl-ms
            baseWebPath=context.getServletContext().getRealPath("\\");
        } 
        this.applicationContext=applicationContext;
    }
}